package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class BasicExceptionCatch {


    @ExceptionHandler(RuntimeException.class)
    public ResponseResult runTimeExceptionHandler(RuntimeException e){
        return ResponseResult.error(500,e.getMessage());
    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException e){
        return ResponseResult.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult leadExceptionHandler(MethodArgumentNotValidException e){

        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
//        String errMsg = "";
//        for (ObjectError allError : allErrors) {
//            if(errMsg.length()>0) {
//                errMsg += ",";
//            }
//            errMsg += allError.getDefaultMessage();
//        }
        String errMsg = allErrors.stream().
                map(ObjectError::getDefaultMessage).
                collect(Collectors.joining(","));

        return ResponseResult.error(400,errMsg);
    }
}
